const path = require('path')
// 导入WebSocket模块:
const WebSocket = require('ws')
// 引用Server类:
const WebSocketServer = WebSocket.Server

// 实例化:
const wss = new WebSocketServer({
  port: 9998
})

const readFileJsonData = require('../utils/read_file_json')
// 开启监听
module.exports.listen = () => {
  wss.on('connection', (ws) => {
    console.log(`[SERVER] connection()`)
    ws.on('message', async (message) => {
      /**
       * message {
       *    action: 'getData',
       *    socketType: 'rankData',
       *    chart: 'rank',
       *    value: ''
       * }
       */

      console.log(`[SERVER] Received: ${message}`)
      let payload = JSON.parse(message)
      switch (payload.action) {
        // 读取表格数据
        case 'getData':
          // 拼接路径
          let chartPath = path.join(
            __dirname,
            '../public/json/' + payload.chart + '.json'
          )

          let res = await readFileJsonData(chartPath)
          payload.data = res
          ws.send(JSON.stringify(payload), (err) => {
            if (err) {
              console.log(`[SERVER] error: ${err}`)
            }
          })
          break
        case 'fullScreen':
          // 广播消息给所有客户端
          wss.clients.forEach((client) => {
            client.send(JSON.stringify(payload))
          })
          break
        // {"action":"changeTheme","socketType":"changeTheme","chart":"","value":""}
        case 'changeTheme':
          // 广播消息给所有客户端
          wss.clients.forEach((client) => {
            console.log(1111111111);
            client.send(JSON.stringify(payload))
          })
          break
      }
    })
  })
}
